package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/axgle/mahonia"
	"math/rand"
	"net"
	"strconv"
	"strings"
)

const BaseNumber = "0123456789"

// RandomNumbers 生成指定位数的随机数
func RandomNumbers(length int) string {
	var number bytes.Buffer
	for i := 0; i < length; i++ {
		intn := rand.Intn(10)
		number.WriteString(BaseNumber[intn : intn+1])
	}
	return number.String()
}

// FirstUpper 字符串首字母大写
func FirstUpper(s string) string {
	if s == "" {
		return ""
	}
	return strings.ToUpper(s[:1]) + s[1:]
}

// FirstLower 字符串首字母小写
func FirstLower(s string) string {
	if s == "" {
		return ""
	}
	return strings.ToLower(s[:1]) + s[1:]
}

// If 三木运算符实现
func If(condition bool, trueVal, falseVal interface{}) interface{} {
	if condition {
		return trueVal
	}
	return falseVal
}

// ToJsonString 将给定结构体转换 json 字符串
func ToJsonString(v interface{}) string {
	marshal, err := json.Marshal(v)
	if err != nil {
		fmt.Printf("Unmarshal with error: %+v\n", err)
		return ""
	}
	return string(marshal)
}

func ToJsonStringGB2312(v interface{}) string {
	marshal, _ := json.Marshal(v)
	encoder := mahonia.NewEncoder("GBK")
	return encoder.ConvertString(string(marshal))
}

// JsonToMap Convert json string to map
func JsonToMap(jsonStr string) map[string]interface{} {
	m := make(map[string]interface{})
	err := json.Unmarshal([]byte(jsonStr), &m)
	if err != nil {
		fmt.Printf("Unmarshal with error: %+v\n", err)
		return nil
	}
	return m
}

// InSliceIndex 字符串在 slice 中的下标，没有返回 -1
func InSliceIndex(items []string, item string) int {
	for i, eachItem := range items {
		if eachItem == item {
			return i
		}
	}
	return -1
}

// GetLocalIp 获取本机网卡 IP
func GetLocalIp() string {
	addrs, err := net.InterfaceAddrs()

	if err != nil {
		return ""
	}

	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}

// FloatDecimal 浮点数格式化
func FloatDecimal(value float64, format string) float64 {
	value, _ = strconv.ParseFloat(fmt.Sprintf(format, value), 64)
	return value
}

// FloatDecimal2 浮点数格式化
func FloatDecimal2(value float64) float64 {
	value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
	return value
}
